<?php
namespace control;
// 产品维修
class aftermarketRegisterClass extends adIndexClass
{
	private const title          = '维修登记';
	private const page           = 'aftermarketRegister';
	private const table          = 'aftermarket';
	private const tableTarget    = 'material';
	private const state          = ['草稿', '已登记'];
	private const workFlow       = '登记';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => '单据编号',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'companyName' => [
                        'name'  => "客户名称",
                        'width' => 150,
                    ],
                    'name'  => [
                        'name'  => "产品名称",
                        'width' => 200,
                    ],
                    'code'  => [
                        'name'  => "产品编码",
                        'width' => 150,
                    ],
                    'repairer'  => [
                        'name'  => "报修人",
                        'width' => 150,
                    ],
                    'type'         => [
                        'name'  => '故障类型',
                        'width' => 100,
                    ],
                    'level'          => [
                        'name'  => '故障等级',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'text'          => [
                        'name'  => '故障描述',
                        'width' => 180,
                    ],
                    'emergency'          => [
                        'name'  => '紧急程度',
                        'width' => 180,
                    ],
                    'repairerTime'          => [
                        'name'  => '报修时间',
                        'width' => 180,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 180,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "单据编号" => text(array("name" => "orderNo")),
                    "客户名称"   => clientProfileClass::kehuSelect(array('title' => '')),
                    "产品名称"   => text(array("name" => "eqName")),
                ],
                [
                    "产品编码"   => text(array("name" => "eqCode")),
                    "报修人"   => text(array("name" => "repairer")),
                    '故障类型'  => select(["name" => "type", 'option' => explode('，', para('aftermarketType'))]),
                ],
                [
                    "故障描述"   => select(["name" => "level", 'option' => explode('，', para('aftermarketLevel'))]),
                    "紧急程度" => select(["name" => "emergency", 'option' => explode('，', para('aftermarketEmergency'))]),
                    "报修时间" => text(['name' => 'repairerTime', 'laydate' => ['range' => '~', 'type' => 'datetime'],]),
                ],
                [
                    "状态"   => select(["name" => "state", 'option' => self::state]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

	/**
	 * 查询表单
	 *
	 * @return string
	 */
	public function home(): string
	{
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('".self::page."','edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        if ($this->power(self::page, "edit")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'registryCancel'})\">取消登记</span>\n";
        }
		return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
	}

	/**
	 * 列表页-查询结果
	 *
	 * @return string
	 */
	public function homeSearch(): string
	{
		$equal = [
			'khid'      => $this->post('khid'),
			'type'      => $this->post('type'),
			'level'     => $this->post('level'),
			'emergency' => $this->post('emergency'),
			'state'     => $this->post('state'),
			'coid'      => self::$coid,
			'workFlow'  => self::workFlow,
		];
		$like  = [
			'orderNo'  => $this->post('orderNo'),
			'repairer' => $this->post('repairer'),
			'text'     => $this->post('text'),
		];
		//生成查询语句
		$where = search([
			"="    => $equal,
			"like" => $like,
		]);
		//生成子查询语句
		$targetWhere = search([
			"like" => [
				'code' => $this->post('eqCode'),
				'name' => $this->post('eqName'),
			],
		]);
		if ($targetWhere) {
			$where .= " and targetId IN (SELECT id  FROM `" . self::tableTarget . "` WHERE 1=1 $targetWhere) ";
		}
		// 时间查询
		if ($this->post('repairerTime')) {
			$where .= self::timeComparison($this->post('repairerTime'), 'time', 'repairerTime');
		}
		if ($this->post('commitTime')) {
			$where .= self::timeComparison($this->post('commitTime'), 'time', 'commitTime');
		}
		if ($this->post('repairDate')) {
			$where .= self::timeComparison($this->post('repairDate'), 'time', 'repairDate');
		}
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
		$page = $this->page(["table" => self::table, "where" => $where, "order" => $orderBy['orderBy']]);
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
		//获取记录
		$url = root . "control/adIndex.html?cla=" . self::page;
		//获取记录
		foreach ($page['array'] as $array) {
			//列表控件
			$dominate  = [
				"box"    => [
					"name" => "listId", "value" => $array['id'],
				],
				"detail" => [
					"title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')",
				],
			];
			$target    = query(self::tableTarget, " id = '$array[targetId]' ","name,code");
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'companyName':
                        $kehu      = query('kehu', " khid = '$array[khid]' ");
                        $row[] = $kehu['companyName'];
                        break;
                    case 'name':
                    case 'code':
                        $row[] = $target[$key];
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
		}
		//控件
		$button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
		//返回
		$json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'];
		return json_encode($json, 320);
	}

	/**
	 * 编辑页
	 *
	 * @return string
	 */
    public function edit()
    {
        $id       = $this->post('id')?:self::getId();
        $info     = query(self::table, " coid = '" . self::$coid . "' AND id = '" . $id . "' ");
        if ($info['targetId']) {
            $material    = query(self::tableTarget, " id = '$info[targetId]' ");
            $mName       = $material['code'] . '-' . $material['name'] . '-' . ($material['model']?:'无');
        } else {
            $mName = '未选择';
        }
        //表单
        $html = $this->layerEdit([
            "table" => [
                [
                    must . '客户' => clientProfileClass::kehuSelect(array('value' => $info['khid'])),
                    must . '产品' => hidden(['name' => 'targetId', 'value' => $info['targetId']])
                        . '<span id="targetName" class="exceed-ellipsis" style="max-width: 80%;">' . $mName . '</span>'
                        . "<span class='del-row-button m-l-10' onclick=\"layer('{$this->get('cla')}','addTarget', {'khid': $(this).parents('form').find('[name=\'khid\']').val()  })\">选择</span>",
                ],
                [
                    must . '报修人' => text(['name' => 'repairer', 'value' => $info['repairer']]),
                    must . '报修人联系电话' => text(['name' => 'repairerTel', 'value' => $info['repairerTel']]),
                ],
                [
                    must . '报修时间' => text(['name' => "repairerTime", 'class' => 'text', 'value' => $info['repairerTime'] ?: $this->time, 'laydate' => ['type' => 'datetime']]),
                    '故障类型' => select(['name' => "type", 'class' => 'text', 'value' => $info['type'], 'option' => explode('，', para('aftermarketType'))]),
                ],
                [
                    '故障等级' => select(['name' => "level", 'class' => 'text', 'value' => $info['level'], 'option' => explode('，', para('aftermarketLevel'))]),
                    '紧急程度' => select(['name' => "emergency", 'class' => 'text', 'value' => $info['emergency'], 'option' => explode('，', para('aftermarketEmergency'))]),
                ],
                [
                    '故障描述' => textarea(['name' => "text", 'class' => 'text', 'value' => $info['text']]),
                ],
                [
                    '故障图片' => fileUploadClass::addImgComponent($id, '故障图片', self::page, self::page . 'EditForm'),
                ],

            ],
        ]);
        $html .= <<<EOT
		<script>
		//选择明细
        function addTarget(){
            $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addTargetEdit', $("form[name='mxForm']").serialize(), function(resp) {
	         if (resp.warn === 2){
	            $("[name='targetId']").val(resp.res.targetId)
                $('#targetName').html(resp.res.name)
	         }else{
	             msg(resp.warn);
	         }
	        },'json');
        }
        function setOption(array){
            let options = `<option>-请选择-</option>\n`
            array.forEach(function (item, key){
                if(typeof key==='number'){
                    options += `<option value="\${item}">\${item}</option>\n`
                }else{
                    options += `<option value="\${key}">\${item}</option>\n`
                }
            })
            return options
        }
        
		</script>
EOT;
        //返回
        return $this->layer(array("title" => L('job.button.editor').self::title, "height" => 450, "html" => $html));
    }

	/**
	 *选择生产产品
	 *
	 * @return bool|string
	 */
	public function addTarget(): bool|string
	{
		if (static::isNull($this->post('khid'))) {
			return json_encode(['warn' => '请先选择客户'], 320);
		}
		$html   =
            materialClass::typeSelect(name: 'typeId') .
			text(["name" => "code", "title" => "产品编码"]) .
			text(["name" => "name", "title" => "产品名称"]) .
			text(["name" => "model", "title" => "规格型号"]) .
			hidden(['name' => 'khid', 'value' => $this->post('khid')]);
		$button = "<input onclick=\"addTarget();$('#" . self::page . "AddTarget').hide()\" type='button' class='searchSub m-l-5' value='提交'>";
		$html   = $this->search($html);
		return $this->layer(["title" => "添加", "height" => 600, "width" => 1000, "zindex" => 3, "html" => $html, "button" => $button]);
	}

	/**
	 *添加产品
	 */
	public function addTargetSearch(): bool|string
	{
		$where = " m.coid = '".self::$coid."' ";
		$like  = [
			'm.name'  => $this->post('name'),
			'm.code'  => $this->post('code'),
			'm.model' => $this->post('model'),
            'm.typePath' => $this->post('typeId'),
		];
		$equal = [
		];
		$where .= search(["like" => $like, "=" => $equal]);
		if ($this->post('khid')) {
			$where .= " AND m.id IN (SELECT materialId FROM `inventory_detail` WHERE orderId IN (SELECT id FROM `inventory` WHERE sourceTable = 'sale_send_order' AND sourceId IN (SELECT id FROM `sale_send_order` WHERE `khid` = '" . $this->post('khid') . "' AND coid = '" . self::$coid . "' )) ) ";
		}
		$page = $this->page([
			'field' => 'm.*',
			"table" => self::tableTarget . ' as m',
			"where" => $where,
			"order" => "time ASC",
		]);
		//获取表头
		$tr[] = ['', '分类', '产品编码', '产品名称', '规格型号'];
		//获取记录
		foreach ($page['array'] as $array) {
			$tr[]         = array(
				"<input name='mxId' value='$array[id]' type='radio' class='radio-bigger'>",
                $array['typeName'],
				$array['code'],
				$array['name'],
				$array['model'],
			);
		}
		$json['html'] = $page['hint'] . "<form name='mxForm'>" . $this->tableMany(array("tr" => $tr, "showSort" => true, "page" => $page['para'])) . "</form>" . $page['button'];
		return json_encode($json, 320);
	}

	/**
	 * 编辑
	 *
	 * @return bool|string
	 */
	public function addTargetEdit(): bool|string
	{
		$mxId = $this->post('mxId');
		if (!$this->power(self::page, 'edit')) {
			$json['warn'] = '你还没有编辑权限';
		} elseif (empty($mxId)) {
			$json['warn'] = '请选择产品';
		} else {
			$target = query(self::tableTarget, "id = '$mxId' ");
			if (!$target['name']) {
				$json['warn'] = '产品不存在';
			} else {
				$json = [
					'warn' => 2,
					'res'  => [
						'name'     => $target['code'] . '-' . $target['name'] . '-' . $target['model'],
						'targetId' => $target['id'],
					],
				];
			}
		}
		return json_encode($json, 320);
	}


	/**
	 * 编辑报错
	 *
	 * @return bool|string
	 */
	public function editEdit(): bool|string
	{
		$id         = $this->post('id') ?: self::getId();
		$fileIdArr  = $this->post('imgId');
		$field      = [
			'workFlow'     => '登记',
			'khid'         => $this->post('khid'),
			'targetId'     => $this->post('targetId'),
			'repairer'     => $this->post('repairer'),
			'repairerTel'  => $this->post('repairerTel'),
			'repairerTime' => $this->post('repairerTime'),
			'type'         => $this->post('type'),
			'level'        => $this->post('level'),
			'emergency'    => $this->post('emergency'),
			'text'         => $this->post('text'),
		];
		$annotation = [
			'workFlow'     => '类型',
			'khid'         => '客户',
			'targetId'     => '产品id',
			'repairer'     => '报修人',
			'repairerTel'  => '报修人电话',
			'repairerTime' => '报修时间',
			'type'         => '故障类型',
			'level'        => '故障等级',
			'emergency'    => '紧急程度',
			'text'         => '故障描述',
		];
		$rules      = [
			'khid'         => 'required',
			'workFlow'     => 'required',
			'targetId'     => 'required',
			'repairer'     => 'required',
			'repairerTel'  => 'required|tel',
			'repairerTime' => 'required',
			// 'type'         => 'required',
			// 'level'        => 'required',
			// 'emergency'    => 'required',
			// 'text'         => 'required',
		];
		$vt         = new \verify();
		$result     = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
		if ($result === false) {
			$json['warn'] = $vt->getErrs()[0]; // 多个规则提示最前面一条
			goto resp;
		}
		$where = " id = '$id' ";
		$info  = query(self::table, $where);
		//判断
		if (!$this->power(self::page, "edit")) {
			$json['warn'] = "你没有编辑" . self::title . "的权限";
		}/* elseif (empty($tpl['id'])) {
			$json['warn'] = "维修信息不存在";
		}*/ else {
			$this->startTrans();
			$isPass = true;//事务通过标志
			if (empty($info['id'])) {
				$orderNo      = codeTemplateClass::generateCode(self::page, [
					'prefix' => 'CPWX' . date('Ymd'),
					'table'  => self::table,
					'field'  => 'orderNo',
					'where'  => '',
				], $field);
				$field        = array_merge($field, [
					'id'      => $id,
					'state'   => '草稿',
					'orderNo' => $orderNo,
					'coid'    => self::$coid,
					'stid'    => $this->control['stid'],
				]);
				$json['warn'] = static::insert(["table" => self::table, "field" => $field]);
			} else {
				$json['warn'] = static::update([
					"table" => self::table,
					"field" => $field,
					"where" => $where,
				]);
			}
			// 更新文件
			if (is_array($fileIdArr)) {
				$warn = update([
					'table' => 'file',
					'field' => ['targetId' => $id],
					'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')",
				]);
				if (!in_array($warn, ['新增成功', '更新成功'])) {
					$json['warn'] = $warn;
					$isPass       = false;
				}
			}
			if (in_array($json['warn'], ["新增成功", "更新成功"]) && $isPass) {
				$this->commitTrans();
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
			} else {
				$this->rollback();
			}
		}

		resp:
		return json_encode($json, 320);
	}

	/**
	 * 详情页
	 *
	 * @return string
	 */
	public function detail(): string
	{
		$info = query(self::table, " coid = '" . self::$coid . "' AND id = '{$this->get('id')}'");
		if (empty($info['id'])) {
			$html = '未找到此' . self::title;
		} else {
			$target    = query(self::tableTarget, " id = '$info[targetId]' ");
			$kehu      = query('kehu', " khid =  '$info[khid]' ", 'companyName');
			//菜单
			$data   = array(
				"id" => $info['id'],
			);
			$button = [];
			if ($info['state'] === '草稿') {
				if ($this->power(self::page, 'edit')) {
					$button[] = [
						"name"  => "编辑",
                        "type" => "弹出层",
                        "cla" => $this->get('cla'),
                        "fun" => "edit",
                        "post" => ["id" => $info['id']],
					];
				}
				if ($this->power(self::page, 'del')) {
					$button[] = [
						"name" => "删除",
						"type" => "弹出层",
						"cla"  => $this->get('cla'),
						"fun"  => "operate",
						"post" => ["act" => 'del', "id" => $info['id'], 'cla' => $this->get('cla')],
					];
				}
				if ($this->power(self::page, 'registry')) {
					$button[] = [
						"name"  => "提交",
						"type"  => "弹出层",
						"cla"   => $this->get('cla'),
						"fun"   => "operate",
						"post"  => ["act" => 'registry', "id" => $info['id']],
						'style' => 'li-btn-blue-bg',
					];
				}
			}
			if (in_array($info['state'], ['已登记', '待派工'])) {
				if ($this->power(self::page, 'registryCancel')) {
					$button[] = [
						"name" => "取消登记",
						"type" => "弹出层",
						"cla"  => $this->get('cla'),
						"fun"  => "operate",
						"post" => ["act" => 'registryCancel', "id" => $info['id'], 'cla' => $this->get('cla')],
					];
				}
				if ($this->power('aftermarketAssign', 'assignOutside')) {
					$button[] = [
						"name" => "委外维修",
						"type" => "弹出层",
						"cla"  => $this->get('cla'),
						"fun"  => "operate",
						"post" => ["act" => 'assignOutside', "id" => $info['id'], 'cla' => $this->get('cla')],
					];
				}
				if ($this->power('aftermarketAssign', 'assign')) {
					$button[] = [
						"name"  => "内部派工",
						"type"  => "弹出层",
						"cla"   => $this->get('cla'),
						"fun"   => "operate",
						"post"  => ["act" => 'assign', "id" => $info['id'], 'cla' => $this->get('cla')],
						'style' => 'li-btn-blue-bg',
					];
				}
			}
			//生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html']          = $this->tableShow(
                [
                    '详细信息' => [
                            [
                                "客户" => $kehu['companyName'],
                                "产品" => $target['code'] . ' - ' . $target['name'] . ' - ' . ($target['model']?:'无'),
                                "报修人"     => self::findStaff($info['repairer']) ?: $info['repairer'],
                                "报修人电话" => $info['repairerTel'],
                            ],
                            [
                                "报修时间"   => $info['repairerTime'],
                                "故障类型" => $info['type'],
                                "故障等级" => $info['level'],
                                "紧急程度" => $info['emergency'],
                            ],
                            [
                                "故障描述" => pre($info['text']),
                            ],
                            [
                                "故障图片" => fileUploadClass::showImg($info['id'], '故障图片'),
                            ],
                        ]
                ]
            );
			// 进度为派工时
			if (in_array($info['workFlow'], ['派工', '维修'])) {
                $data['html']          .= $this->tableShow(
                    [
                        '派工信息' => [
                            [
                                "维修部门" => $info['processingDepartment'],
                                "维修人"   => self::findStaff($info['processors']),
                                "派工时间" => $info['commitTime'],
                            ],
                            [
                                "处理意见" => pre($info['processingResult']),
                            ],
                        ]
                    ]
                );
			}
			// 进度为维修时
			if ($info['workFlow'] == '维修') {
                $data['html']          .= $this->tableShow(
                    [
                        '维修记录' => [
                            [
                                "维修日期"      => $info['repairDate'],
                                "维修时长（min）" => $info['repairTime'],
                                "维修结果"      => $info['repairResult'],
                            ],
                            [
                                "维修措施" => pre($info['repairMeasure']),
                            ],
                        ]
                    ]
                );
				// 关联领用单
				$tr[]   = ['配件编码', '名称', '规格型号', '单位', '数量', '单价（' . static::$unit . '）', '金额（' . static::$unit . '）', '备注'];
				$result = find([
					'table' => 'parts_inventory as p, parts_inventory_detail as d',
					'field' => 'd.*',
					'where' => " p.id = d.orderId AND p.classify=0 AND  p.state='已确认' AND p.sourceId = '{$info['id']}' ",
				]);
				foreach ($result['array'] as $array) {
					$parts    = query('material', " id = '$array[partsId]' ");
					if (static::isNull($parts['id'])) {
						continue;
					}
					// 减去退货部分
					$returnNum = static::total([
						'sql'   => "SELECT IFNULL(SUM(num), 0) AS total FROM `parts_inventory_detail` ",
						'where' => " `sourceTable` = 'parts_inventory_detail' AND `sourceId` IN (SELECT id FROM `parts_inventory` WHERE classify=0 AND  state='已确认' AND sourceId = '{$info['id']}' ) ",
					]);
					$price     = inventoryBalanceClass::unitPrice($parts['id']);
					$num       = $array['num'] - $returnNum;
					$money     = round($num * $price, 2);
					$tr[]      = [$parts['code'], $parts['name'], $parts['model'], $parts['unit'], $num, $price, $money, $array['text']];
				}
                $data['html'] .= $this->detailList([
                    'title' => '配件领用',
                    'html' => $this->listTable(array('tr' => $tr, 'showEmpty' => true)),
                ]);
			}
            $data['html']          .= $this->tableShow(
                [
                    '系统信息' => [
                        [
                            "单据编号" => $info['orderNo'],
                            "创建人"   => self::findStaff($info['stid']),
                            "创建时间" => $info['time'],
                            "更新时间" => $info['updateTime'],
                        ],
                        [

                            "状态"     => $info['state'],
                        ],
                    ]
                ]
            );
			//生成页面
			$html = $this->tab($data);
		}
		//返回
		return $html;
	}

	// 操作中转
	public function operate(): bool|string
	{
		$act    = $this->post('act') ?? '';
		$pwd    = '';
		$height = null;
		$append = [];
		$word   = false;
		$page   = self::page;
		// 需要密码
		switch ($act) {
			case 'registry':
				$act      = 'registry';
				$msg      = '登记';
				$title    = '是否登记此维修单？';
				$function = 'changeWorkFlow';
				$form     = self::page . 'OperateForm, listForm, detailForm';
				$power    = '';
				$word     = true;
				$append   = [
					[
						'&nbsp' => hidden(['name' => 'act', 'value' => $act]),
					],
				];
				break;
			case 'registryCancel':
				$act      = 'registryCancel';
				$msg      = '取消登记';
				$title    = '是否取消登记此维修单？';
				$function = 'changeWorkFlow';
				$form     = self::page . 'OperateForm, listForm, detailForm';
				$power    = '';
				$append   = [
					[
						'&nbsp' => hidden(['name' => 'act', 'value' => $act]),
					],
				];
				$word     = true;
				break;
			case 'assignOutside':
				$page     = 'aftermarketAssign';
				$act      = 'assignOutside';
				$msg      = '委外维修';
				$title    = '';
				$function = 'changeWorkFlow';
				$append   = [
					[
						must . '维修单位' => text(['name' => 'processingDepartment']),
					],
					[
						must . '维修人' => text(['name' => 'processors']),
					],
					[
						must . '维修人联系电话' => text(['name' => 'processorsTel']),
					],
					[
						'处理意见：' => textarea(['name' => 'processingResult', 'class' => 'width300']) . hidden(['name' => 'act', 'value' => $act]),
					],
				];
				$form     = self::page . 'OperateForm, listForm, detailForm';
				$power    = '';
				$height   = 360;
				$word     = true;
				break;
			case 'assign':
				$act      = 'assign';
				$page     = 'aftermarketAssign';
				$msg      = '内部派工';
				$title    = '';
				$function = 'changeWorkFlow';
				$append   = [
					[
						must . '维修人员' => selectMultiple(['table' => 'staff', "title" => '请选择', 'sqlField' => 'name', 'sqlId' => 'stid', 'name' => 'processors']),
					],
					[
						'处理意见：' => textarea(['name' => 'processingResult', 'class' => 'width300']) . hidden(['name' => 'act', 'value' => $act]),
					],
				];
				$form     = self::page . 'OperateForm, listForm, detailForm';
				$power    = '';
				$height   = 270;
				$word     = true;
				break;
			default:
				$act      = 'del';
				$msg      = '删除' . self::title;
				$title    = self::page . 'Delete';
				$function = 'delete';
				$form     = self::page . 'OperateForm, listForm, detailForm';
				$power    = '';
				break;
		}
		if (!$this->power($page, $act)) {
			$_SESSION['warn'] = '你还没有' . $msg . '的权限';
			$json             = [
				'warn' => 2,
				'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
			];
		} else {
			return $this->confirm([
				'title'    => $title,
				'function' => $function,
				'form'     => $form,
				'power'    => $power,
				'pwd'      => $pwd,
				'word'     => $word,
				'append'   => $append,
				'height'   => $height,
			]);
		}

		resp:
		return json_encode($json, 320);
	}

	/**
	 * 处理结果
	 *
	 * @return bool|string
	 */
	public function changeWorkFlow(): bool|string
	{
		$array = $this->post('listId') ?? $this->post('id');
		$act   = $this->post('act');
		$page  = match ($act) {
			'assignOutside', 'assign'    => 'aftermarketAssign',
			'registry', 'registryCancel' => self::page,
			default                      => self::page,
		};
		$json  = [];
		if (!$this->power($page, $act)) {
			$json['warn'] = "你没有此权限的权限";
		} elseif (empty($array)) {
			$json['warn'] = "你一条记录都没有选择呢";
		} else {
			$text  = '';
			$x     = 0;
			$array = is_array($array) ? $array : [$array];
			switch ($act) {
				case 'registry':
					$opt        = '登记';
					$field      = [
						'workFlow' => '登记',
						'state'    => '已登记',
					];
					$annotation = [
						'workFlow' => '进度',
						'state'    => '状态',
					];
					$rules      = [
						'workFlow' => 'required',
						'state'    => 'required',
					];
					break;
				case 'registryCancel':
					$opt        = '取消登记';
					$field      = [
						'workFlow' => '登记',
						'state'    => '草稿',
					];
					$annotation = [
						'workFlow' => '进度',
						'state'    => '状态',
					];
					$rules      = [
						'workFlow' => 'required',
						'state'    => 'required',
					];
					break;
				case 'assignOutside':
					$opt        = '委外维修';
					$field      = [
						'processingDepartment' => $this->post('processors'),
						'processors'           => $this->post('processors'),
						'processorsTel'        => $this->post('processorsTel'),
						'processingResult'     => $this->post('processingResult'),
						'commitTime'           => $this->date,
						'classify'             => '委外维修',
						'workFlow'             => '派工',
						'state'                => '已派工',
					];
					$annotation = [
						'processingDepartment' => '维修单位',
						'processors'           => '维修人员',
						'processorsTel'        => '维修人电话',
						'processingResult'     => '处理意见',
						'workFlow'             => '进度',
						'state'                => '状态',
					];
					$rules      = [
						'processingDepartment' => 'required',
						'processors'           => 'required',
						'processorsTel'        => 'required|tel',
						'workFlow'             => 'required',
						'state'                => 'required',
					];
					break;

				case 'assign':
					$opt        = '内部派工';
					$field      = [
						'processingDepartment' => self::findStaffDepartment($this->post('processors')),
						'processors'           => $this->post('processors'),
						'processingResult'     => $this->post('processingResult'),
						'commitTime'           => $this->date,
						'classify'             => '内部派工',
						'workFlow'             => '派工',
						'state'                => '已派工',
					];
					$annotation = [
						'processors'           => '维修人员',
						'processingResult'     => '处理意见',
						'workFlow'             => '进度',
						'state'                => '状态',
					];
					$rules      = [
						'processors'           => 'required',
						'workFlow'             => 'required',
						'state'                => 'required',
					];
					break;
				default:
					$json['warn'] = "未知操作";
					goto resp;
			}
			// 校验是否符合规则
			$vt     = new \verify();
			$result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
			if ($result === false) {
				$json['warn'] = $vt->getErrs()[0]; // 多个规则提示最前面一条
				goto resp;
			}
			foreach ($array as $id) {
				$where = " id = '$id' AND coid = '" . self::$coid . "' ";
				$info  = query(self::table, $where);
				if (static::isNull($info['id'])) {
					continue;
				}
				$warn = static::update([
					'table' => self::table,
					'field' => $field,
					'where' => $where,
				]);
				if (in_array($warn, ['更新成功', '新增成功'])) {
					$text .= "管理员{$this->control['name']}{$opt}了一条" . self::title . "：ID【{$id}】<br>";
					$x++;
				}
			}
			// 写入日志
			$this->logText(["type" => self::page, "text" => $text]);
			$_SESSION['warn'] = "处理了{$x}条" . self::title;
			$json['warn']     = 2;
			$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
		}
		resp:
		return json_encode($json, 320);
	}

	/**
	 * 删除
	 *
	 * @return bool|string
	 */
	public function delete(): bool|string
	{
		$array = $this->post('listId') ?? $this->post('id');
		if (!$this->power(self::page, "del")) {
			$json['warn'] = "你没有删除的权限";
		} elseif (empty($array)) {
			$json['warn'] = "你一个数据都没有选择呢";
		} else {
			$text  = "";
			$x     = 0;
			$array = is_array($array) ? $array : [$array];
			foreach ($array as $id) {
				$info = query(self::table, " coid = '" . self::$coid . "' AND id = '$id' ");
				if ($info['state'] == '已审核') {
					$warn = "删除失败：已审核，暂不能删除";
				} else {
					//最后删除基本参数
					delete(["table" => self::table, "where" => " id = '$id' "]);
					//返回
					$warn = "删除成功";
					$x++;
				}
				$text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
			}
			//添加日志
			$text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
			$this->logText(array("type" => self::page, "text" => $text));
			$_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
			$json['warn']     = 2;
			$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
		}
		return json_encode($json, 320);
	}
}
